package com.ccc.hotsearch.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.ccc.hotsearch.dto.HotSearchData;
import com.ccc.hotsearch.dto.PlatformData;
import com.ccc.hotsearch.dto.Summary;
import com.ccc.hotsearch.model.HotItem;
import com.ccc.hotsearch.model.PlatformTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class HotSearchManager {

    @Autowired(required = false)
    private List<HotSearchService> hotSearchServices = new ArrayList<>(); // 添加默认值

    private final TimedCache<String, Object> cache = // 改为Object类型
            CacheUtil.newTimedCache(TimeUnit.MINUTES.toMillis(2));

    @PostConstruct
    public void init() {
        cache.schedulePrune(TimeUnit.MINUTES.toMillis(1));
        // 如果没有自动注入，手动添加服务
        if (hotSearchServices.isEmpty()) {
            hotSearchServices.add(new WeiboHotSearchServiceImpl());
            hotSearchServices.add(new BaiduHotSearchServiceImpl());
        }
    }

    /**
     * 获取所有平台热搜
     */
    public HotSearchData getAllHotSearch() {
        String cacheKey = "all_hot_search";
        Object cachedData = cache.get(cacheKey);

        if (cachedData instanceof HotSearchData) {
            return (HotSearchData) cachedData;
        }

        HotSearchData data = new HotSearchData();
        List<PlatformData> platforms = new ArrayList<>();
        Map<String, Integer> platformCounts = new HashMap<>();

        // 并行获取所有平台数据
        List<CompletableFuture<PlatformData>> futures = hotSearchServices.stream()
                .map(service -> CompletableFuture.supplyAsync(() -> {
                    try {
                        List<HotItem> items = service.getHotSearch();
                        PlatformData platformData = new PlatformData();
                        platformData.setPlatform(service.getPlatformType());
                        platformData.setItems(items);
                        platformData.setTotal(items.size());
                        platformData.setUpdateTime(System.currentTimeMillis());
                        platformData.setNextUpdate("2分钟后");
                        return platformData;
                    } catch (Exception e) {
                        System.err.println("获取" + service.getPlatformType().getName() + "热搜失败: " + e.getMessage());
                        return null;
                    }
                }))
                .collect(Collectors.toList());

        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        for (CompletableFuture<PlatformData> future : futures) {
            PlatformData platformData = future.join();
            if (platformData != null) {
                platforms.add(platformData);
                platformCounts.put(platformData.getPlatform().getName(), platformData.getTotal());
            }
        }
        data.setPlatforms(platforms);

        // 设置汇总信息
        Summary summary = new Summary();
        summary.setTotalItems(platforms.stream().mapToInt(PlatformData::getTotal).sum());
        summary.setTotalPlatforms(platforms.size());
        summary.setPlatformCounts(platformCounts);

        data.setSummary(summary);

        cache.put(cacheKey, data);
        return data;
    }

    /**
     * 获取单个平台热搜
     */
    public PlatformData getHotSearchByPlatform(PlatformTypeEnum platform) {
        String cacheKey = "hot_search_" + platform.getCode();
        Object cachedData = cache.get(cacheKey);

        if (cachedData instanceof PlatformData) {
            return (PlatformData) cachedData;
        }

        Optional<HotSearchService> serviceOpt = hotSearchServices.stream()
                .filter(s -> s.getPlatformType() == platform)
                .findFirst();

        if (serviceOpt.isPresent()) {
            List<HotItem> items = serviceOpt.get().getHotSearch();
            PlatformData platformData = new PlatformData();
            platformData.setPlatform(platform);
            platformData.setItems(items);
            platformData.setTotal(items.size());
            platformData.setUpdateTime(System.currentTimeMillis());
            platformData.setNextUpdate("2分钟后");

            cache.put(cacheKey, platformData);
            return platformData;
        }

        return null;
    }

    /**
     * 搜索跨平台热搜
     */
    public List<HotItem> searchHotSearch(String keyword) {
        HotSearchData allData = getAllHotSearch();
        List<HotItem> results = new ArrayList<>();

        for (PlatformData platformData : allData.getPlatforms()) {
            for (HotItem item : platformData.getItems()) {
                if (item.getTitle() != null && item.getTitle().toLowerCase().contains(keyword.toLowerCase())) {
                    results.add(item);
                }
            }
        }

        return results.stream()
                .sorted(Comparator.comparing(item -> {
                    try {
                        return Integer.parseInt(item.getRank());
                    } catch (NumberFormatException e) {
                        return Integer.MAX_VALUE;
                    }
                }))
                .collect(Collectors.toList());
    }

    /**
     * 清除缓存
     */
    public void clearCache() {
        cache.clear();
    }
}
